package com.snow;


import com.google.protobuf.ByteString;
import com.snow.proto.group_list.GroupInfo;
import com.snow.proto.group_list.GroupListInfoRequest;
import com.snow.proto.group_list.GroupListInfoResponse;
import com.snow.proto.group_list.GroupListServiceGrpc;
import io.grpc.stub.StreamObserver;
import model.Group_Dao;

 import java.io.IOException;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
 import java.util.List;

public class MyChat_Groupimpl extends GroupListServiceGrpc.GroupListServiceImplBase {
    @Override
    public void getGroupListInfoByUserId(GroupListInfoRequest request, StreamObserver<GroupListInfoResponse> responseObserver) {
        int user_id = request.getUserId();
        ResultSet rs=Group_Dao.searchGroup(user_id);
        String name = null;
        String  avatar_type = null;
        Blob avatar = null;
        ByteString byteString = null;
        GroupListInfoResponse groupListInfoResponse ;
        List<GroupInfo> list = new ArrayList<>();
        try {
            while (rs.next()){
                name = rs.getString("name");
                 avatar_type = rs.getString("avatar_type");
                avatar = rs.getBlob("avatar");
                byteString=ByteString.readFrom(avatar.getBinaryStream());
                GroupInfo groupInfo =GroupInfo.newBuilder().setName(name).setAvatarType(avatar_type).setAvatar(byteString).build();
                list.add(groupInfo);
        }

                groupListInfoResponse = GroupListInfoResponse.newBuilder().addAllGroupInfo(list).build();
            responseObserver.onNext(groupListInfoResponse);
            responseObserver.onCompleted();

        }catch (SQLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
